from typing import List

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload

from src.application.proxy.enums import AuthorizationType, ProxyStatus
from src.application.server.enums import ServerPrivacy, ServerType
from src.infrastructure.db.models import Proxy
from src.infrastructure.db.services.servers import get_server
from src.infrastructure.utils.helpers import generate_proxy


async def get_proxy(session: AsyncSession, proxy_id: int, joined: bool = True) -> Proxy:
    q = select(Proxy).where(Proxy.id == proxy_id)

    if joined:
        q = q.options(joinedload(Proxy.orders), joinedload(Proxy.server))

    res = await session.execute(q)

    return res.scalar()


async def change_expired_proxy(session: AsyncSession, proxies: list[Proxy]) -> None:
    for proxy in proxies:
        server = await get_server(session, proxy.server_id)
        proxy = await get_proxy(session, proxy.id, joined=True)
        login, password, reload_link = await generate_proxy()

        if server.proxy_type == ServerType.mobile:
            if server.proxy_privacy == ServerPrivacy.private:
                proxy.login = login
                proxy.password = password
                proxy.reload_link = reload_link
                proxy.authorization_type = AuthorizationType.by_password
                proxy.reload_period = 5
            else:
                # proxy.reload_type = "by_link"
                # proxy.reload_period = 0
                proxy.authorization_type = None

        if len(proxy.orders) <= 1:
            # Если этот заказ единственный
            proxy.status = ProxyStatus.available

    await session.commit()
